﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SL8.SL.Extensions
{
    /// <summary>
    /// OOB 模式下拖动服务扩展
    /// </summary>
    public static class MainWindowDragMoveService
    {
        public static readonly DependencyProperty IsDragMoveProperty =
            DependencyProperty.RegisterAttached("IsDragMove",
            typeof(bool),
            typeof(MainWindowDragMoveService),
            new PropertyMetadata(false, new PropertyChangedCallback(MainWindowDragMoveService.OnIsDragMovePropertyChange)));

        public static bool GetIsDragMove(DependencyObject d)
        {
            return (bool)d.GetValue(MainWindowDragMoveService.IsDragMoveProperty);
        }

        public static void SetIsDragMove(DependencyObject d, bool value)
        {
            d.SetValue(MainWindowDragMoveService.IsDragMoveProperty, value);

            MainWindowDragMoveService.UnsubscribeEvents(d);
            if (value)
            {
                MainWindowDragMoveService.SubscribeEvents(d);
            }
        }

        private static void OnIsDragMovePropertyChange(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (System.ComponentModel.DesignerProperties.IsInDesignTool)
            {
                return;
            }

            if ((bool)e.NewValue)
            {
                MainWindowDragMoveService.SubscribeEvents(d);
            }
            else
            {
                MainWindowDragMoveService.UnsubscribeEvents(d);
            }
        }

        /// <summary>
        /// 注销模版事件
        /// </summary>
        private static void UnsubscribeEvents(DependencyObject d)
        {
            UIElement uiElement = d as UIElement;
            if (uiElement != null)
            {
                uiElement.MouseLeftButtonDown -= new MouseButtonEventHandler(uiElement_MouseLeftButtonDown);
            }
        }

        static void uiElement_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (Application.Current.IsRunningOutOfBrowser && Application.Current.HasElevatedPermissions)
            {
                Application.Current.MainWindow.DragMove();
            }
        }

        /// <summary>
        /// 注册事件
        /// </summary>
        private static void SubscribeEvents(DependencyObject d)
        {
            UIElement uiElement = d as UIElement;
            if (uiElement != null)
            {
                uiElement.MouseLeftButtonDown += new MouseButtonEventHandler(uiElement_MouseLeftButtonDown);
            }
        }
    }
}
